<?php


namespace App\Controller;
use App\Model\User;
use App\Util\Baidu\AipSdk\AipImageClassify;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 * Class ApiController
 * @package App\Controller
 * @AutoController
 */
class ApiController extends AbstractController
{

    // 你的 APPID AK SK
    const APP_ID = '23781907';
    const API_KEY = 'm7XT16mis3Lq2RGklNgAc6xF';
    const SECRET_KEY = 'WbhRDoSI5gBCjnam8EkKFumPZGY5clGg';
    private $redis;

    public function __construct(){
        $container = ApplicationContext::getContainer();
        if(!$this->redis) {
            $this->redis = $container->get(\Hyperf\Redis\Redis::class);
        }
    }
    public function test1()
    {
        $client = new AipImageClassify(self::APP_ID, self::API_KEY, self::SECRET_KEY);
        $image = file_get_contents('https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2641679094,1826525725&fm=26&gp=0.jpg');
        $res = $client->redwine($image);
        return $res;
    }


    public function handleUserRegister(RequestInterface $request){
        $param = $request->inputs(['user_name','user_password','user_mobile','verify_code']);
        $container = ApplicationContext::getContainer();
        $generator = $container->get(IdGeneratorInterface::class);

        $user = [
            'user_id' => $generator->generate(),
            'user_name' => $param['user_name'] ?? '',
            'user_mobile' => $param['user_mobile'],
            'age' => $param['age'] ?? 18,
            'gender' => $param['gender'] ?? 1,
            'password' => password_hash($param['user_password'],PASSWORD_DEFAULT)
        ];
        $userModel = new User();
        $userModel->user_id = $generator->generate();
        $userModel->user_mobile = $user['user_mobile'];
        $userModel->user_name = $user['user_name'];
        $userModel->age = $user['age'];
        $userModel->gender = $user['gender'];
        $userModel->password = $user['password'];

        $res = $userModel->save();
        if($res){
            return '注册成功';
        }
        return '注册成功';
    }

    public function handleLogin(RequestInterface $request){
        $param = $request->inputs(['user_name','user_mobile','password']);

        $wh = [
            ['user_name','=',$param['user_name']]
        ];
        $userInfo = User::query()->where($wh)->first();
        if(!$userInfo){
            return '账号或密码错误';
        }
        if($userInfo && password_verify($param['password'],$userInfo->password) === false){
            return '账号或密码错误';
        }


        return [
            'user_id' => $userInfo->user_id
        ];
    }


}